package com.contactmgr.listadapter;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.contactmgr.R;
import com.contactmgr.logObjects.Contact;
import com.contactmgr.logObjects.Contact.TYPE;

public class ContactListAdapter extends ArrayAdapter<Contact> {
	private List<Contact> contact;
	int resourceid;
	Context context;

	public ContactListAdapter(Context context, int textViewResourceId, List<Contact> contact) {
		super(context, textViewResourceId, contact);
		this.context = context;
		this.contact = contact;
		this.resourceid = textViewResourceId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup viewGroup) {
		Contact curContact = contact.get(position);
		if (null == convertView) {
			// inflate xml layout
			LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflator.inflate(resourceid, null);

		}
		TextView name = (TextView) convertView.findViewById(R.id.contactname);
		name.setText(curContact.getDisplayName());
		// TextView email =
		// (TextView)convertView.findViewById(R.id.contactemail);
		TextView phone = (TextView) convertView.findViewById(R.id.contactphoneDef);

		Map<TYPE, String> phones = curContact.getPhone();
		phone.setText(getSet(phones));
		return convertView;
	}

	private String getSet(Map<TYPE, String> map) {

		String phones = "";
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			Object key = it.next();
			String val = map.get(key);
			if (isSet(val)) {
				phones += key + " : " + val;
			}
			if (it.hasNext()) {
				phones += "\n";
			}
		}
		return phones;
	}

	private boolean isSet(String str) {
		if (str == null || str.trim().equals("")) {
			return false;
		} else {
			return true;
		}
	}

}
